/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ucjava.chat.commserve.rmi.server;

import com.ucjava.chat.commserve.rmi.common.Message;
import com.ucjava.chat.commserve.rmi.common.PrefStore;
import com.ucjava.chat.commserve.rmi.common.RMIChatConstants;
import java.sql.Timestamp;
import java.util.Date;
import java.util.LinkedList;
import java.util.Queue;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Handles storage of messages that are awaiting archiving..
 *
 * For now, the archiving consists of deleting old messages; later, we can think
 * about adding code to move them to db or file storage.
 *
 * @author tony
 */
public class MessageArchiver
{
    // Place to keep track of preferences/configurations

    PrefStore prefStore;
    private Queue<MessageWithTimestamp> archivingQueue;

    /**
     * constructor
     */
    public MessageArchiver()
    {

        prefStore = PrefStore.makePrefStore();
        archivingQueue = new LinkedList<MessageWithTimestamp>();
        

        ClearArchive clearArc = new ClearArchive();
        Thread clearArcThread = new Thread(clearArc, "Archive Clearing Thread");
        clearArcThread.start();
    }

    /**
     * Add a message to our queue, where it will await archiving.
     *
     * @param msg
     */
    // Add a message to our queue:
    public void enqueueMessage(Message msg)
    {
        MessageWithTimestamp mts = new MessageWithTimestamp(msg);
        synchronized (archivingQueue)
          {
            archivingQueue.add(mts);
          }
    }

    /**
     * Inner class to handle "garbage collection." This run() method deletes old
     * messages from the archivingQueue. In a production system, it might save
     * them to a database instead.
     *
     * The run() method loops until allDone is true. Other threads can call
     * setAllDone to stop this thread.
     */
    public class ClearArchive implements Runnable
    {
        // Use this to signal when it's
        // time to quit:

        private boolean allDone;

        public void setAllDone(boolean b)
        {
            allDone = b;
        }

//        @Override
//        public void run() {
//            try { 
//                Thread.sleep(600000);
//            } catch (InterruptedException ex) {
//                Logger.getLogger(MessageArchiver.class.getName()).log(Level.SEVERE, null, ex);
//            }     
//            
//            archivingQueue.clear();
//     
//        }
        @Override
        public void run()
        {
            while (!allDone)
              {
                try
                  {
                    Thread.sleep(prefStore.getArchiveCheckInterval());
                  } catch (InterruptedException ex)
                  {
                    Logger.getLogger(
                            MessageArchiver.class.getName()).log(Level.SEVERE,
                            null, ex);
                  }
                printStatus();
                archivingQueue.clear();
              }



        } // end ClearArchive#run()

        // For debugging, print some information
        // each time through. NOTE: Remove this
        // before deployment -- it is BAD PRACTICE
        // to do i/o while synchronized.
        private void printStatus()
        {
            System.out.println("Archiving Queue Status:"
                    + RMIChatConstants.ENDLINE);
            System.out.println(new Date().toString()
                    + RMIChatConstants.ENDLINE);
            System.out.println("Number of Messages"
                    + MessageArchiver.this.archivingQueue.size()
                    + RMIChatConstants.ENDLINE);
        }
    } // end class ClearArchive

    // Inner class which gives us a Message with a Timestamp:
    private class MessageWithTimestamp
    {

        private Message message;
        private Timestamp timestamp;
        // constructor:

        public MessageWithTimestamp(Message msg)
        {
            message = msg;
            // generate a timestamp of now
            timestamp = new Timestamp(new Date().getTime());
        }

        public Timestamp getTimestamp()
        {
            return timestamp;
        }

        public Message getMessage()
        {
            return message;
        }
    } // end inner class MessageWithTimestamp

} // end class MessageArchiver

